package cn.otrue.patienthealthmanager.adapter;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DoctorChatActivity;
import cn.otrue.patienthealthmanager.bean.DoctorBaseinfo;
import cn.otrue.patienthealthmanager.bean.HistoryChat;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.DensityUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class FindDoctorPrivateFragmentAdpater extends BaseAdapter {

	private List<DoctorBaseinfo> all;
	private LayoutInflater inflater;
	private Context context;
	private TextView tw_doctor_one;
	private TextView tw_doctor_two;
	private TextView tw_doctor_shree;
	private TextView tw_consult;
	private TextView tw_attention;
	private AlertDialog alertDialog;

	private int cid = 0;

	public void ImageSet(String imgurl, ImageView img_headPhoto) {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.iv_user_photo)
				.showImageOnFail(R.drawable.iv_user_photo)
				.showImageForEmptyUri(R.drawable.iv_user_photo)
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(
						new RoundedBitmapDisplayer(DensityUtil.dip2px(context,
								40))).build();
		ImageLoader.getInstance().displayImage(imgurl, img_headPhoto, options);
	}

	Handler removeHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {
				Toast.makeText(context, "取消关注成功", 0).show();
				all.remove(cid);
				FindDoctorPrivateFragmentAdpater.this.notifyDataSetChanged();
			} else {
				Toast.makeText(context, "取消关注失败", 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}
	};

	private ImageView pe_head_image;

	public FindDoctorPrivateFragmentAdpater(Context context,
			List<DoctorBaseinfo> all) {
		super();
		this.all = all;
		this.context = context;
		inflater = LayoutInflater.from(this.context);
		DBTools.db = DbUtils.create(context);

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return all.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(final int arg0, View arg1, ViewGroup arg2) {
		arg1 = inflater.inflate(R.layout.item_doctor_siren_list, null);
		final DoctorBaseinfo doctor = all.get(arg0);
		pe_head_image = (ImageView) arg1.findViewById(R.id.pe_head_image);

		tw_doctor_one = (TextView) arg1.findViewById(R.id.tw_doctor_one);
		tw_doctor_two = (TextView) arg1.findViewById(R.id.tw_doctor_two);
		tw_doctor_shree = (TextView) arg1.findViewById(R.id.tw_doctor_shree);
		tw_attention = (TextView) arg1.findViewById(R.id.tw_attention);
		tw_consult = (TextView) arg1.findViewById(R.id.tw_consult);
		tw_consult.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String jid = doctor.getJid();
				Intent intent = new Intent();
				// 购买服务之后必做事件

				try {
					HistoryChat oldHistoryListModel = DBTools.db
							.findFirst(Selector
									.from(HistoryChat.class)
									.where("patientUser", "=",
											MyConst.getACCOUNT())
									.and(WhereBuilder.b("doctorUser", "=",
											doctor.getAliasAccount())));

					if (oldHistoryListModel != null) {
						DBTools.db.delete(oldHistoryListModel);
					}
					HistoryChat newHistory = new HistoryChat(MyConst
							.getACCOUNT(), doctor.getAliasAccount(), 0, "",
							MyConst.FILE_TXT, new Date(), 0);
					DBTools.db.save(newHistory);

					intent.putExtra("from", jid);
					intent.setClass(context, DoctorChatActivity.class);
					context.startActivity(intent);
				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		if (doctor.getIsAttention().equals("1")
				&& !TextUtils.isEmpty(MyConst.getACCOUNT())) {
			tw_attention.setBackgroundResource(R.drawable.jiaguanzhu_on);
		} else {
			tw_attention.setBackgroundResource(R.drawable.jiaguanzhu);
		}

		String url = doctor.getHeadimg();

		ImageSet(url, pe_head_image);

		tw_attention.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				View dialogView = initDataInputDialog(new DataDialogListener(),
						arg0);
				alertDialog = DialogUtil.showDialog(context, dialogView, true);

			}

		});

		String address = doctor.getInHospital();
		if (address != null) {
			if (address.indexOf("-") == -1) {
				tw_doctor_two.setText(address);

			} else {

				String[] dateA = address.split("-");
				tw_doctor_two.setText(dateA[3]);
			}
		}

		tw_doctor_one.setText(doctor.getRealname());

		tw_doctor_shree.setText(doctor.getGood_at_subject());

		return arg1;

	}

	private View initDataInputDialog(DataDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.dialog_input_daget, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		tv_catt_dialogRight.setTag(i);
		return view;

	}

	public class DataDialogListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			alertDialog.dismiss();
			switch (v.getId()) {

			case R.id.tv_catt_dialogLeft:// 取消
				break;
			case R.id.tv_catt_dialogRight:// 确定

				final int tag = Integer.parseInt(v.getTag().toString());
				final DoctorBaseinfo doctor = all.get(tag);
				alertDialog.dismiss();
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("sender", MyConst.getACCOUNT());
				map.put("receiver", doctor.getAliasAccount());
				TransferParameter parameter = new TransferParameter();
				parameter.setData(map);
				new HttpServer().post(HttpCons.DELETE_DOCTOR_ATTENTION_INFO,
						parameter, removeHandler);

				break;
			}

		}

	}

	public static boolean removeUser(Roster roster, String userName) {
		try {

			Collection<RosterEntry> rosterEntryList = roster.getEntries();
			String userOpenName = "";
			for (RosterEntry rosterEntry : rosterEntryList) {
				String user = rosterEntry.getUser();

				if (user.equals(userName)) {
					userOpenName = rosterEntry.getName();
					break;
				}
			}
			if (userOpenName != "") {
				RosterEntry entry = roster.getEntry(userOpenName);
				roster.removeEntry(entry);
			} else {
				return true;
			}

			return true;
		} catch (Exception e) {

			return false;
		}
	}

}
